<script lang="ts" setup>
import DataTable from "@/components/data-table/index.vue";
import {h, onMounted, onUnmounted, ref} from "vue";
import router from '@/router'
import {ElAlert, ElButton, ElLoading, ElMessage, ElMessageBox, ElScrollbar, ElRadioGroup, ElRadio} from "element-plus";
import {service} from "@/utils";
import EditProcess from './edit-process.vue'
import {Session} from "@/views/applet/ssh/interface";
import ShellConsole from "./shell-console.vue";

const tableRef = ref<InstanceType<typeof DataTable>>()
const editProcessRef = ref<InstanceType<typeof EditProcess>>()
const shellConsoleRef = ref<InstanceType<typeof ShellConsole>>()
const props = defineProps<{session: Session}>()

const columns = ref([
    { prop: 'title', label: '标题', width: 200, tooltip: true},
    { prop: 'name', label: '进程标识', minWidth: 400, tooltip: true},
    { prop: 'position', label: '文件位置', width: 350, tooltip: true},
    { prop: 'pid', label: 'PID', minWidth: 80},
    { prop: 'startup', label: '启动命令', width: 250, tooltip: true, visible: false},
    { prop: 'shutdown', label: '关闭命令', width: 250, tooltip: true, visible: false},
    { prop: 'uri', label: '服务地址', width: 200, tooltip: true,
        render: ({row}: any) => {
            if (row.uri) {
                return h(ElButton, {link: true, tag: 'a', type: 'primary', onClick: () => toComponent(row)}, {default: () => row.uri})
            }
        }
    },
    {
        type: "action", width: 250, maxCollapseButtons: 2,
        render: [
            {label: '编辑', icon: 'el-icon-edit-pen', onClick: ({row}: any)=> onEditProcess('update', row)},
            {label: '删除', icon: 'el-icon-delete', onClick: ({row}: any)=> onDeleteProcess(row), type: 'danger'},
            {label: '复制', icon: 'el-icon-copy-document', onClick: ({row}: any)=> onEditProcess('copy', row)},
            {label: '启动', icon: 'el-icon-switch-button', onClick: ({row}: any)=> onCommand('startup', row)},
            {label: '关闭', icon: 'el-icon-close', onClick: ({row}: any)=> onCommand('shutdown', row)},
        ]
    },
])

const onEditProcess = (operate:string, data?:any) => {
    let form;
    if (operate === 'update') {
        form = {...data};
    } else if (operate === 'copy') {
        form = {...data};
        form.id = null;
    }
    editProcessRef.value?.open({
        data: form,
        type: operate === 'update'? 'put':'post',
        confirm: (resolve: (value: any)=> void, form: any, operate: AxiosMethod) => {
            form.name = form.name.join(';')
            service[operate]('/ssh/process', form).then(({code}) => {
                if (code === 200) {
                    tableRef.value?.refresh()
                }
                resolve(code);
            })
        },
    })
}

const onShellConsole = () => {
    shellConsoleRef.value?.show();
}

const onOpenSftp = () => {
    const {href} = router.resolve({name: 'FileZilla', query: {uid: props.session.id}});
    window.open(href, "_blank");
}

const onDeleteProcess = (data: any) => {
    service.confirm(`确定删除${data.title}进程信息?`, {
        url: '/ssh/process',
        data: {id: data.id},
        success: tableRef.value?.refresh
    })
}

const onCommand = (type:string, data?: any) => {
    if (data) {
        if (type === 'startup' && data.pid) {
            ElMessage.warning(`${data.title}应用进程（Pid=${data.pid}）已存在`)
        } else if (type === 'shutdown' && !data.pid) {
            ElMessage.warning(`${data.title}应用进程已不存在`)
        } else {
            ElMessageBox.confirm(`确定执行[${type === 'startup' ? '启动' : type === 'shutdown' ? '关闭' : ''}]指令?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const text = ref("Loading(29s)...")
                const loadingInstance = ElLoading.service({
                    lock: true,
                    text: text
                })
                let seconds = 29;
                const interval = setInterval(function() {
                    if (seconds === 0) {
                        clearInterval(interval);
                    } else {
                        seconds--;
                        text.value = 'Loading(' + seconds + 's)...';
                    }
                }, 1000);

                const form = {
                    sessionId: props.session.id,
                    processes: [data.id]
                };
                service.put(`/ssh/process/${type}`, form, {timeout: 30000}).then(({code, data}) =>  {
                    if (code === 200) {
                        let children: Array<any> = [];
                        data.forEach((item: any) => {
                            item['closable'] = false
                            item['class'] = 'alert-command'
                            children.push(h(ElAlert, item))
                        })
                        ElMessageBox({
                            title: '执行结果',
                            showConfirmButton: false,
                            customClass: 'message-box__command',
                            message: h(ElScrollbar, {maxHeight: '60vh'}, {default: ()=> children}),
                        })
                    }
                }).finally(() => {
                    clearInterval(interval);
                    loadingInstance.close();
                })
            });
        }
    } else {
        ElMessage.warning("请先选择进程信息")
    }
}

const visible = ref(true);
const onTableLoading = (status: boolean, code: number) => {
    visible.value = !(!status && code === 500);
}

const toComponent = (data: any) => {
    if (data.mode === 'API') {
        const checked = ref<string>('Zookeeper')
        if (data.title.toLowerCase().indexOf('hadoop') > -1 || data.title.toLowerCase().indexOf('hdfs') > -1){
            checked.value = 'Hadoop'
        }
        ElMessageBox({
            title: '选择组件',
            confirmButtonText: '进入',
            message: () =>{
                return h(ElRadioGroup, {
                    modelValue: checked.value,
                    'onUpdate:modelValue': (val: string) => {
                        checked.value = val
                    },
                }, {
                    default: () => {
                        return [
                            h(ElRadio, {value:"Zookeeper"}, {default: () => 'Zookeeper'}),
                            h(ElRadio, {value:"Hadoop"}, {default: () => 'Hadoop'}),
                        ]
                    }
                })
            },
        }).then(() => {
            const {href} = router.resolve({name: checked.value, query: {uid: data.uriId}});
            window.open(href, "_blank");
        }).catch(()=>({}))

    } else {
        window.open(data.uri, "_blank");
    }
}

onUnmounted(() => {
    service.delete(`/ssh/session/exit`, {id: props.session.id})
})
</script>

<template>
    <div style="height: calc(100vh - 134px);">
        <data-table ref="tableRef" :api="`/ssh/process?sessionId=${session.id}`" :columns="columns" :pagination="false" @loading="onTableLoading">
            <template #button>
                <el-button v-if="visible" icon="el-icon-plus" @click="onEditProcess('create')">新增进程</el-button>
                <el-button v-if="visible" icon="el-icon-chat-line-square" @click="onShellConsole()">控制台</el-button>
                <el-button v-if="visible" v-auth="'secure:ssh:view:sftp'" @click="onOpenSftp()"/>
<!--                <el-button v-if="visible" icon="el-icon-tools" @click="onEditProcess('create')">应用工具</el-button>-->
            </template>
        </data-table>
    </div>
    <edit-process ref="editProcessRef" :session="session"/>

    <shell-console ref="shellConsoleRef" :session="session"/>
</template>

<style>

.message-box__command {
    width: 65% !important;
    max-width: unset !important;
}

.message-box__command .el-message-box__container{
    display: unset;
}

.alert-command {
    white-space: pre-wrap;
}
</style>
